package com.yxq.mdt.app.modules.socialcontact.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.material.appbar.AppBarLayout;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseFragment;
import com.yxq.mdt.app.modules.bottomsheet.PublishBottomSheetFragment;
import com.yxq.mdt.app.modules.message.ui.MessageTabActivity;
import com.yxq.mdt.app.modules.personal.bean.PublishResult;
import com.yxq.mdt.app.modules.search.ui.SearchCommunityActivity;
import com.yxq.mdt.app.modules.socialcontact.adapter.CommunityCentreAdapter;
import com.yxq.mdt.app.modules.socialcontact.adapter.ExamplePagerAdapter;
import com.yxq.mdt.app.modules.socialcontact.adapter.MainSocialTopAdapter;
import com.yxq.mdt.app.modules.socialcontact.bean.CommunityCentreBean;
import com.yxq.mdt.app.modules.socialcontact.bean.MainSocialTopBean;
import com.yxq.mdt.app.modules.socialcontact.model.MainSocialContactModel;
import com.yxq.mdt.app.modules.socialcontact.presenter.MainSocialContactContract;
import com.yxq.mdt.app.modules.socialcontact.presenter.MainSocialContactPresenter;
import com.yxq.mdt.app.modules.socialcontact.ui.activity.CircleRecommendListAc;
import com.yxq.mdt.app.modules.socialcontact.ui.activity.CircleTheHomepageAc;
import com.yxq.mdt.app.modules.socialcontact.ui.activity.SocialPersonalHomepageAc;
import com.yxq.mdt.app.modules.socialcontact.ui.fragment.main.AttentionFragment;
import com.yxq.mdt.app.modules.socialcontact.ui.fragment.main.MainSocialFragment;
import com.yxq.mdt.app.modules.socialcontact.ui.fragment.main.NearbyFragment;
import com.yxq.mdt.app.modules.socialcontact.ui.fragment.main.RecommendFragment;
import com.yxq.mdt.app.modules.socialcontact.ui.fragment.main.VideoFragment;
import com.yxq.mdt.app.utils.ScaleTransitionPagerTitleView;
import com.yxq.mdt.app.widgets.NonSwipeableViewPager;

import net.lucode.hackware.magicindicator.FragmentContainerHelper;
import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jzvd.Jzvd;

/**
 * @author L
 * @time 2019-12-18
 * @describe 社区首页$
 */
public class MainSocialContactFragmentCoordinatorLayout extends BaseFragment<MainSocialContactPresenter> implements MainSocialContactContract.View {
    @BindView(R.id.social_in_a_batch)
    LinearLayout socialInABatch;
    @BindView(R.id.magic_indicator_recycler_top)
    RecyclerView magicIndicatorRecyclerTop;
    @BindView(R.id.look_all)
    TextView lookAll;
    @BindView(R.id.magic_indicator_recycler_center)
    RecyclerView magicIndicatorRecyclerCenter;
    @BindView(R.id.magic_indicator)
    MagicIndicator magicIndicator;
    @BindView(R.id.app_bar)
    AppBarLayout appBar;
    @BindView(R.id.view_pager)
    NonSwipeableViewPager viewPager;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    MainSocialTopAdapter mainSocialTopAdapter;
    CommunityCentreAdapter commonNavigatorAdapter;
    ExamplePagerAdapter mExamplePagerAdapter;
    RecommendFragment recommendFragment;
    NearbyFragment nearbyFragment;
    MainSocialFragment mainSocialFragment;
    VideoFragment videoFragment;
    AttentionFragment attentionFragment;

    PublishBottomSheetFragment publishBottomSheetFragment;
    private static final String[] CHANNELS = new String[]{"推荐", "附近", "圈子", "视频", "关注"};
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.search_layout_left)
    RelativeLayout searchLayoutLeft;
    @BindView(R.id.main_social_search_text)
    TextView mainSocialSearchText;
    @BindView(R.id.social_search_layout)
    RelativeLayout socialSearchLayout;
    @BindView(R.id.main_social_massage_img)
    RelativeLayout mainSocialMassageImg;
    @BindView(R.id.social_layout_search)
    RelativeLayout socialLayoutSearch;
    @BindView(R.id.social_recommended_circles)
    LinearLayout socialRecommendedCircles;
    @BindView(R.id.magic_publish)
    ImageView magicPublish;
    private List<String> mDataList = Arrays.asList(CHANNELS);
    private List<Fragment> mFragments = new ArrayList<Fragment>();
    int currentTabIndex = 0;//当前选中的Tab页面

    @Override
    protected int attachLayoutId() {
        return R.layout.fragment_social_contact_layout;
    }

    @Override
    protected MainSocialContactPresenter getPresenter() {
        return new MainSocialContactPresenter(this, new MainSocialContactModel());
    }

    @Override
    public void initView(View view) {
        new Handler().postDelayed(() -> initView(), 50);
    }

    @Override
    public void initData() {
        EventBus.getDefault().register(this);
    }

    /**
     * 初始化界面
     */
    private void initView() {
        //顶部推荐用户
        mainSocialTopAdapter = new MainSocialTopAdapter(R.layout.main_community_top_item, null);
        magicIndicatorRecyclerTop.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        magicIndicatorRecyclerTop.setAdapter(mainSocialTopAdapter);
        //推荐圈子
        magicIndicatorRecyclerCenter.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        commonNavigatorAdapter = new CommunityCentreAdapter(R.layout.main_community_centre_item, null);
        magicIndicatorRecyclerCenter.setAdapter(commonNavigatorAdapter);
        //初始化Fragment子页面
        initFragments();
        mExamplePagerAdapter = new ExamplePagerAdapter(getChildFragmentManager(), mFragments, mDataList);
        viewPager.setAdapter(mExamplePagerAdapter);
        //初始化指示器
        initMagicIndicator();

        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            //推荐用户
            if (mPresenter != null) {
                mPresenter.getMaybeInterest();
            }
        });
//        loadCache();
        new Handler().postDelayed(() -> refreshLayout.autoRefresh(), 500);

    }

    /**
     * 刷新子Fragment页面数据
     */
    private void refreshTabFragment() {
        switch (currentTabIndex) {
            case 0:
                //推荐页面刷新
                recommendFragment.refresh();
                break;
            case 1:
                //附近页面刷新
                nearbyFragment.refresh();
                break;
            case 2:
                //圈子页面刷新
                mainSocialFragment.refresh();
                break;
            case 3:
                //视频页面刷新
                videoFragment.refresh();
                break;
            case 4:
                //关注页面刷新
                attentionFragment.refresh();
                break;
        }
    }

    /**
     * 滑动页面至顶部并刷新数据
     */
    public void refresh() {
        if(refreshLayout!=null){
            refreshLayout.autoRefresh();
        }
    }

    /**
     * 预加载缓存数据
     */
    private void loadCache() {
        String userStr = Hawk.get("sc-user", null);
        //推荐用户
        if (userStr != null) {
            MainSocialTopBean mainSocialTopBean = JSON.parseObject(userStr, MainSocialTopBean.class);
            setItemAttentionInfo(mainSocialTopBean);
        }
        String groupStr = Hawk.get("sc-group", null);
        //推荐圈子
        if (groupStr != null) {
            CommunityCentreBean communityCentreBean = JSON.parseObject(groupStr, CommunityCentreBean.class);
            setCommunityCentre(communityCentreBean);
        }
    }

    /**
     * 推荐用户展示
     *
     * @param mainSocialTopBean 关注
     */
    private void setItemAttentionInfo(MainSocialTopBean mainSocialTopBean) {
        if (mainSocialTopBean == null) {
            return;
        }
        mainSocialTopAdapter.setNewData(mainSocialTopBean.getList());
        mainSocialTopAdapter.setOnItemChildClickListener((BaseQuickAdapter adapter, View view12, int position) -> {
            switch (view12.getId()) {
                case R.id.community_relation:
                    //关注
                    mPresenter.setInterestRelation(mainSocialTopBean.getList().get(position).getUserId(), 1, 1);
                    break;
                default:
            }
        });
        mainSocialTopAdapter.setOnItemClickListener((adapter, view1, position) -> {
            //跳转个人中心
            Intent intent = new Intent(mContext, SocialPersonalHomepageAc.class);
            intent.putExtra("userId", mainSocialTopBean.getList().get(position).getUserId());
            startActivity(intent);
        });
    }

    /**
     * 推荐圈子展示
     */
    private void setCommunityCentre(CommunityCentreBean communityCentreBean) {
        if (communityCentreBean != null && communityCentreBean.getList() != null && communityCentreBean.getList().size() > 0) {
            socialRecommendedCircles.setVisibility(View.VISIBLE);
            commonNavigatorAdapter.setNewData(communityCentreBean.getList());
        } else {
            socialRecommendedCircles.setVisibility(View.GONE);
        }
        commonNavigatorAdapter.setOnItemClickListener((adapter, view, position) -> {
            Intent intent = new Intent(mContext, CircleTheHomepageAc.class);
            intent.putExtra("CircleName", communityCentreBean.getList().get(position).getGroupname());
            intent.putExtra("id", communityCentreBean.getList().get(position).getId());
            startActivity(intent);
        });
    }

    //初始化fragment addFragment
    private void initFragments() {

        //推荐
        recommendFragment = new RecommendFragment();
        Bundle recommendBundle = new Bundle();
        recommendBundle.putString(SocialStateFragment.EXTRA_TEXT, CHANNELS[0]);
        recommendFragment.setArguments(recommendBundle);
        mFragments.add(recommendFragment);

        //附近
        nearbyFragment = new NearbyFragment();
        Bundle nearbyFragmentBundle = new Bundle();
        nearbyFragmentBundle.putString(MainSocialFragment.EXTRA_TEXT, CHANNELS[2]);
        nearbyFragment.setArguments(nearbyFragmentBundle);
        mFragments.add(nearbyFragment);

        //圈子
        mainSocialFragment = new MainSocialFragment();
        Bundle bundle2 = new Bundle();
        bundle2.putString(MainSocialFragment.EXTRA_TEXT, CHANNELS[2]);
        mainSocialFragment.setArguments(bundle2);
        mFragments.add(mainSocialFragment);

        //视频
        videoFragment = new VideoFragment();
        Bundle videoBundle = new Bundle();
        videoBundle.putString(SocialStateFragment.EXTRA_TEXT, CHANNELS[3]);
        videoFragment.setArguments(videoBundle);
        mFragments.add(videoFragment);

        //关注
        attentionFragment = new AttentionFragment();
        Bundle attentionBundle = new Bundle();
        attentionBundle.putString(SocialStateFragment.EXTRA_TEXT, CHANNELS[4]);
        attentionFragment.setArguments(attentionBundle);
        mFragments.add(attentionFragment);

    }

    private void initMagicIndicator() {
        CommonNavigator commonNavigator = new CommonNavigator(mContext);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ScaleTransitionPagerTitleView(context); //使用自定义
                simplePagerTitleView.setNormalColor(Color.BLACK);
                simplePagerTitleView.setSelectedColor(Color.BLACK);
                simplePagerTitleView.setText(mDataList.get(index));
                simplePagerTitleView.setTextSize(20);
                simplePagerTitleView.setOnClickListener(v -> viewPager.setCurrentItem(index));
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator linePagerIndicator = new LinePagerIndicator(context);
                linePagerIndicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                linePagerIndicator.setLineWidth(UIUtil.dip2px(context, 36));
                linePagerIndicator.setLineHeight(UIUtil.dip2px(context, 2));
                linePagerIndicator.setColors(Color.parseColor("#FD4343"));
                return linePagerIndicator;
            }
        });
        magicIndicator.setNavigator(commonNavigator);
        LinearLayout titleContainer = commonNavigator.getTitleContainer(); // must after setNavigator
        titleContainer.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        titleContainer.setDividerDrawable(new ColorDrawable() {
            @Override
            public int getIntrinsicWidth() {
                return UIUtil.dip2px(mContext, 0);
            }
        });
        final FragmentContainerHelper fragmentContainerHelper = new FragmentContainerHelper(magicIndicator);
        fragmentContainerHelper.setInterpolator(new OvershootInterpolator(0.1f));
        fragmentContainerHelper.setDuration(0);
        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                currentTabIndex = position;
                fragmentContainerHelper.handlePageSelected(position);
            }
        });
        viewPager.setOffscreenPageLimit(5);

    }

    @OnClick({R.id.main_social_search_text, R.id.main_social_massage_img, R.id.social_in_a_batch, R.id.magic_publish, R.id.look_all})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.main_social_search_text:
                //搜索
                Intent intent = new Intent(mContext, SearchCommunityActivity.class);
                startActivity(intent);
                break;
            case R.id.main_social_massage_img:
                //消息
                intent = new Intent(mContext, MessageTabActivity.class);
                startActivity(intent);
                break;
            case R.id.social_in_a_batch:
                //换一批 刷新推荐用户
                mPresenter.getMaybeInterest();
                break;
            case R.id.magic_publish:
                //发布弹出框
                publishBottomSheetFragment = new PublishBottomSheetFragment("", "");
                publishBottomSheetFragment.show(getChildFragmentManager(), "publishBottomSheetFragment");
                break;
            case R.id.look_all:
                //全部圈子
                intent = new Intent(mContext, CircleRecommendListAc.class);
                startActivity(intent);
                break;

        }
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void onLoadInterestSuccess(MainSocialTopBean mainSocialTopBean) {
        if (mainSocialTopBean != null) {
            Hawk.put("sc-user", JSON.toJSONString(mainSocialTopBean));
        }
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        setItemAttentionInfo(mainSocialTopBean);
        //推荐圈子
        mPresenter.getHomeRecommendGroup("1", "3");
    }

    @Override
    public void onLoadInterestFailed() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
    }

    @Override
    public void onLoadRelationSuccess(String s) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        //获取推荐联系人
        mPresenter.getMaybeInterest();
    }

    @Override
    public void onLoadRelationFailed() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
    }

    @Override
    public void onLoadHomeRecommendSuccess(CommunityCentreBean communityCentreBean) {
        if (communityCentreBean != null) {
            Hawk.put("sc-group", JSON.toJSONString(communityCentreBean));
        }
        setCommunityCentre(communityCentreBean);
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        refreshTabFragment();
    }

    @Override
    public void onLoadHomeRecommendFailed() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onEvent(PublishResult result) {
        //接收以及处理数据
        refresh();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            Jzvd.releaseAllVideos();
        }
    }
}
